In the PowerShell programming language, a script block is a collection of statements or expressions that can be used as a single unit. A script block can accept arguments and return values.
{<statement list>} #or { Param([type]$Parameter1 [,[type]$Parameter2]) <statement list> }
A script block is an instance of a Microsoft .NET Framework type System.Management.Automation.ScriptBlock. Commands can have script block parameter values. For example, the Invoke-Command cmdlet has a ScriptBlock parameter that takes a script block value,
Invoke-Command -ScriptBlock { Get-Process } Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 999 28 39100 45020 262 15.88 1844 communicator 721 28 32696 36536 222 20.84 4028 explorer ...
Invoke-Command can also execute script blocks that have parameter blocks. Parameters are assigned by position using the ArgumentList parameter.
Invoke-Command -ScriptBlock { param($p1, $p2) "p1: $p1" "p2: $p2" } -ArgumentList "First", "Second" p1: First p2: Second
You can use variables to store and execute script blocks.
$a = { Get-Service BITS } Invoke-Command -ScriptBlock $a Status Name DisplayName ------ ---- ----------- Running BITS Background Intelligent Transfer Ser...
Like Invoke-Command, the call operator executes the script block in a child scope. The call operator can make it easier for you to use parameters with your script blocks.
$a ={ param($p1, $p2) "p1: $p1" "p2: $p2" } &$a -p2 "First" -p1 "Second"
You can store the output from your script blocks in a variable using assignment.
PS> $a = { 1 + 1} PS> $b = &$a PS> $b 2
PS> $a = { 1 + 1} PS> $b = Invoke-Command $a PS> $b 2
Install exe on Remote Server
Invoke-Command -ComputerName server01 -ScriptBlock { Start-Process c:\windows\temp\installer.exe -ArgumentList '/silent' -Wait }
Change File Extension
#Rename File Extension param($Folder) Write-Host "Before Renaming files...`n`n" Get-ChildItem $Folder Get-ChildItem "$Folder\*.txt" | Rename-Item -NewName { $_.name -Replace '.txt','.bak' } Write-Host "`n`nAfter Renaming files...`n`n" Get-ChildItem $Folder